<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>数据表管理</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
	textarea{
		resize:none;
	}
	</style>
	<script type="text/javascript">
		$(document).ready(function() {
			//$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				},
				rules:{
					name:{
						remote: {
						    url: $("#ctx").val()+"/ins/insTable/getByName",     //后台处理程序
						    type: "post",               //数据发送方式
						    dataType: "json",           //接受数据格式   
						    data: {                     //要传递的数据
						        name: function() {
						            return $("#name").val();
						        },
						        id: function(){
						        	return $("#id").val();
						        }
						    }
						}
					}
				},
				messages:{
					name:{
						remote:"该数据表主名称已存在！"
					}
				}
			});
			//选中模板
			$("#templates").change(function(){
				if($(this).val() != ''){
					confirmx("选择模板将清空数据表当前信息，确定吗？",useTemplate);
				}
			});
		});
		
		function addRow(list, idx, tpl, row){
			$(list).append(Mustache.render(tpl, {
				idx: idx, delBtn: true, row: row
			}));
			$(list+idx).find("select").each(function(){
				$(this).val($(this).attr("data-value"));
			});
			$(list+idx).find("input[type='checkbox'], input[type='radio']").each(function(){
				var ss = $(this).attr("data-value").split(',');
				for (var i=0; i<ss.length; i++){
					if($(this).val() == ss[i]){
						$(this).attr("checked","checked");
					}
				}
			});
			//预录入值
			console.log(row.preValues);
			$("#insFieldList"+idx+"_preValues").html(row.preValues);
			//参数类型
			$("#insFieldList"+idx+"_type").on("change",function(){
				if($(this).val()=='2'){
					$("#insFieldList"+idx+"_numberButton").removeAttr("disabled");
				}else{
					$("#insFieldList"+idx+"_numberButton").attr("disabled","disabled");
				}
			});
			$("#insFieldList"+idx+"_numberButton").on("click",function(){
				var btn = $(this);
				var numberFrom = $("#insFieldList"+idx+"_numberFrom").val();//btn.siblings(".numberFrom").val();
				var numberTo = $("#insFieldList"+idx+"_numberTo").val();
				var enableNumberRange = $("#insFieldList"+idx+"_enableNumberRange").val();
				var digit = $("#insFieldList"+idx+"_digit").val();
				var url = "${ctx}/ins/insTable/numberRange?numberFrom="+numberFrom+"&numberTo="+numberTo+"&enableNumberRange="+enableNumberRange+"&digit="+digit;
				top.$.jBox.open("iframe:"+url, "数值范围",810,$(top.document).height()-120,{
	                buttons:{"提交":"ok", "关闭":true}, bottomText:"数值范围",submit:function(v, h, f){
	                    var code;
	                    if (v=="ok"){
	                    	// 执行保存
	                        //loading('正在提交，请稍等...');
	                    	var flag = h.find("iframe")[0].contentWindow.submitForm();
	                    	if(flag){
	                    		var numberFrom = h.find("iframe")[0].contentWindow.$("#numberFrom").val();
								var numberTo = h.find("iframe")[0].contentWindow.$("#numberTo").val();
								var enableNumberRange=h.find("iframe")[0].contentWindow.$("#enableNumberRange").prop("checked");
								var digit = h.find("iframe")[0].contentWindow.$("#digit").val();
								$("#insFieldList"+idx+"_numberFrom").val(numberFrom);
								$("#insFieldList"+idx+"_numberTo").val(numberTo);
								$("#insFieldList"+idx+"_enableNumberRange").val(enableNumberRange?"1":"0");
								$("#insFieldList"+idx+"_digit").val(digit);
								top.$.jBox.close(true);
	                    	}
	                        return false;
	                    }
	                }, loaded:function(h){
	                    $(".jbox-content", top.document).css("overflow-y","hidden");
	                }, closed:function(){
	                }
	            });
			});
		}
		function delRow(obj, prefix){
			var id = $(prefix+"_id");
			var rid = $(prefix+"_rid");
			var delFlag = $(prefix+"_delFlag");
			var frequently = $(prefix+"_frequently");
			if (id.val() == ""){
				$(obj).parent().parent().remove();
			}else if(delFlag.val() == "0"){
				delFlag.val("1");
				$(obj).html("&divide;").attr("title", "撤销删除");
				$(obj).parent().parent().addClass("error");
			}else if(delFlag.val() == "1"){
				delFlag.val("0");
				$(obj).html("&times;").attr("title", "删除");
				$(obj).parent().parent().removeClass("error");
			}
			//删除常用字段的select选项
			if(frequently.val()=="1"){
				$("#fieldList option[value="+rid.val()+"]").attr("selected", "");
			}
		}
		function submitForm(){
			if($("#inputForm").valid()){
				$("#inputForm").submit();
			}
		}
		//设置邮箱收件人
		function setReceiveIds(tableId){
			var ids = $("#idsArr").val();
			top.$.jBox.open("iframe:${ctx}/ins/insTable/setReceiveIds?id=${insTable.id}&ids="+ids, "选择人员",810,$(top.document).height()-240,{
				buttons:{"确定选择":"ok", "清除已选":"clear", "关闭":true}, bottomText:"选择需要发送邮件的人员。",submit:function(v, h, f){
					var pre_ids = h.find("iframe")[0].contentWindow.pre_ids;
					var ids = h.find("iframe")[0].contentWindow.ids;
					//nodes = selectedTree.getSelectedNodes();
					if (v=="ok"){
						// 删除''的元素
						if(ids[0]==''){
							ids.shift();
							pre_ids.shift();
						}
						/* if(pre_ids.sort().toString() == ids.sort().toString()){
							top.$.jBox.tip("尚未选择任何人员！", 'info');
							return false;
						}; */
				    	// 执行保存
				    	var idsArr = "";
				    	for (var i = 0; i<ids.length; i++) {
				    		idsArr = (idsArr + ids[i]) + (((i + 1)== ids.length) ? '':',');
				    	}
				    	$('#idsArr').val(idsArr);
					} else if (v=="clear"){
						h.find("iframe")[0].contentWindow.clearAssign();
						return false;
	                }
				}, loaded:function(h){
					$(".jbox-content", top.document).css("overflow-y","hidden");
				}
			});
		}
	</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/ins/insTable/">数据表列表</a></li>
		<li class="active"><a href="${ctx}/ins/insTable/form?id=${insTable.id}&newTable=newTable">数据表<shiro:hasPermission name="ins:insTable:edit">${not empty insTable.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="ins:insTable:edit">查看</shiro:lacksPermission></a></li>
	</ul><br/>
	<form:form id="inputForm" modelAttribute="insTable" action="${ctx}/ins/insTable/save" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<input type="hidden" id="ctx" value="${ctx}"/>
		<sys:message content="${message}"/>		
		<div class="control-group">
			<label class="control-label">主名称：</label>
			<div class="controls">
				<form:input path="name" htmlEscape="false" maxlength="64" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">次名称：</label>
			<div class="controls">
				<form:input path="fullName" htmlEscape="false" maxlength="64" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">分类：</label>
			<div class="controls">
			<sys:treeselect id="parent" name="category.id" value="${insTable.category.id}" labelName="insTablecategory.name" labelValue="${insTable.category.name}"
					title="父级分类" url="/ins/insCategory/treeData" extId="${insCategory.id}" cssClass="" allowClear="true" dataMsgRequired="分类必选"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">数据表模板：</label>
			<div class="controls">
				<select id="templates" class="input-xlarge">
					<option value="">---可根据模板初始化数据表---</option>
					<c:forEach items="${templates}" var="template">
						<option value="${template.id}">${template.name}</option>
					</c:forEach>
				</select>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">表标识：</label>
			<div class="controls">
				<input type="text" value="${insTable.tableId}" class="input-xlarge" readonly/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">版本号：</label>
			<div class="controls">
				<input type="text" value="${insTable.version}" class="input-xlarge" readonly/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">收件人选择：</label>
			<div class="controls">
				<input type="hidden" id="idsArr" value="${insTable.receiveIds}" name="receiveIds"/>
				<input id="setReceiveButton" class="btn btn-primary" onclick="setReceiveIds('${insTable.id}');" type="button" value="点此设置"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">参数列表：</label>
			<div class="controls">
				<table id="contentTable" class="table table-striped table-bordered table-condensed">
					<thead>
						<tr>
							<th class="hide"></th>
							<th>参数名称</th>
							<th>占位符</th>
							<th>参数类型</th>
							<th>预录入</th>
							<th>排序</th>
							<th>默认值</th>
							<th>必填</th>
							<th>唯一</th>
							<th>索引</th>
							<shiro:hasPermission name="ins:insTable:edit"><th width="10">&nbsp;</th></shiro:hasPermission>
						</tr>
					</thead>
					<tbody id="insFieldList">
					</tbody>
					<shiro:hasPermission name="ins:insTable:edit"><tfoot>
						<tr>
							<td colspan="10">
								<a href="javascript:" onclick="addRow('#insFieldList', insFieldRowIdx, insFieldTpl);insFieldRowIdx = insFieldRowIdx + 1;" class="btn">新增</a>
								<span id="selectSpan">
									<select id="fieldList" multiple="true" class="input-xlarge">
											<c:forEach items="${fieldList}" var="field">
												<option value="${field.id}">${field.name}</option>
											</c:forEach>
									</select>
								</span>
							</td>
						</tr>
					</tfoot></shiro:hasPermission>
				</table>
				<script type="text/template" id="insFieldTpl">//<!--
						<tr id="insFieldList{{idx}}">
							<td class="hide">
								<input id="insFieldList{{idx}}_id" name="insFieldList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
								<input id="insFieldList{{idx}}_rid" class="rid" type="hidden" value="{{row.rid}}"/>
								<input id="insFieldList{{idx}}_frequently" type="hidden" value="{{row.frequently}}"/>
								<input id="insFieldList{{idx}}_delFlag" name="insFieldList[{{idx}}].delFlag" type="hidden" value="0"/>
							</td>
							<td>
								<input id="insFieldList{{idx}}_name" name="insFieldList[{{idx}}].name" type="text" value="{{row.name}}" maxlength="64" class="input-mini required"/>
							</td>
							<td>
								<input id="insFieldList{{idx}}_code" name="insFieldList[{{idx}}].code" type="text" value="{{row.code}}" maxlength="64" class="input-mini" onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"/>
							</td>
							<td>
								<!--<input id="insFieldList{{idx}}_type" name="insFieldList[{{idx}}].type" type="text" value="{{row.type}}" maxlength="2" class="input-small required"/>-->
								<input type="hidden" class="numberFrom" id="insFieldList{{idx}}_numberFrom" name="insFieldList[{{idx}}].numberFrom" value="{{row.numberFrom}}"/>
								<input type="hidden" class="numberTo" id="insFieldList{{idx}}_numberTo" name="insFieldList[{{idx}}].numberTo" value="{{row.numberTo}}"/>
								<input type="hidden" class="enableNumberRange" id="insFieldList{{idx}}_enableNumberRange" name="insFieldList[{{idx}}].enableNumberRange" value="{{row.enableNumberRange}}"/>
								<input type="hidden" class="digit" id="insFieldList{{idx}}_digit" name="insFieldList[{{idx}}].digit" value="{{row.digit}}"/>
								<select id="insFieldList{{idx}}_type" name="insFieldList[{{idx}}].type" data-value="{{row.type}}" class="input-small required fieldType" ind="{{idx}}">
									<option value="1">字符串</option>
									<option value="2">数字</option>
									<option value="3">年月日时分秒</option>
									<option value="4">年月日</option>
									<option value="5">年月</option>
								</select><input id="insFieldList{{idx}}_numberButton" type="button" ind="{{idx}}" value="数值限制" class="numberButton btn" disabled/>
							</td>
							<td>
								<span><input class="preInput" checked id="insFieldList{{idx}}_preInput0" name="insFieldList[{{idx}}].preInput" type="radio" value="0" data-value="{{row.preInput}}"><label for="insFieldList{{idx}}_preInput0">录入</label></span>
								<span><input class="preInput" id="insFieldList{{idx}}_preInput1" name="insFieldList[{{idx}}].preInput" type="radio" value="1" data-value="{{row.preInput}}"><label for="insFieldList{{idx}}_preInput1">选择</label></span>
								<span><input class="preInput" id="insFieldList{{idx}}_preInput2" name="insFieldList[{{idx}}].preInput" type="radio" value="2" data-value="{{row.preInput}}"><label for="insFieldList{{idx}}_preInput1">计算</label></span>
								<span><textarea disabled id="insFieldList{{idx}}_preValues" name="insFieldList[{{idx}}].preValues" rows="1" maxlength="1000" class="input-small ">{{row.preValues}}</textarea></span>
							</td>
							<td>
								<input id="insFieldList{{idx}}_sort" name="insFieldList[{{idx}}].sort" type="text" value="{{row.sort}}" class="input-mini " onkeyup="this.value=this.value.replace(/[^\d]/g,'');"/>
							</td>
							<td>
								<input id="insFieldList{{idx}}_defaultValue" name="insFieldList[{{idx}}].defaultValue" type="text" value="{{row.defaultValue}}" maxlength="64" class="input-mini"/>
							</td>
							<td>
								<div><input class="dis" checked id="r{{idx}}0" name="insFieldList[{{idx}}].required" type="radio" value="0" data-value="{{row.required}}"><label for="insFieldList{{idx}}_required0">非必填</label></div>
								<div><input class="dis" id="r{{idx}}1" name="insFieldList[{{idx}}].required" type="radio" value="1" data-value="{{row.required}}"><label for="insFieldList{{idx}}_required1">必填</label></div>
							</td>
							<td>
								<div><input class="dis" checked id="u{{idx}}0" name="insFieldList[{{idx}}].uniquely" type="radio" value="0" data-value="{{row.uniquely}}"><label for="insFieldList{{idx}}_uniquely0">可重复</label></div>
								<div><input class="dis" id="u{{idx}}1" name="insFieldList[{{idx}}].uniquely" type="radio" value="1" data-value="{{row.uniquely}}"><label for="insFieldList{{idx}}_uniquely1">唯一</label></div>
							</td>
							<td>
								<input type="checkbox" ind="{{idx}}" value="1" data-value="{{row.indexed}}" class="indexed"/>
								<input type="hidden" class="hidden" value="{{row.indexed}}" name="insFieldList[{{idx}}].indexed"/>
							</td>
							<shiro:hasPermission name="ins:insTable:edit"><td class="text-center" width="10">
								{{#delBtn}}<span class="close" onclick="delRow(this, '#insFieldList{{idx}}')" title="删除">&times;</span>{{/delBtn}}
							</td></shiro:hasPermission>
						</tr>//-->
					</script>
				<script type="text/javascript">
					/* if($("#id").val()!=""){
						$("#selectSpan").hide();
					} */
					var insFieldRowIdx = 0, insFieldTpl = $("#insFieldTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
					$(document).ready(function() {
						$("#fieldList").select2({
							placeholder: "常用参数"
						});
						var fieldList = ${fns:toJson(fieldList)};
						var data = ${fns:toJson(insTable.insFieldList)};
						$("#fieldList").on("select2-selecting",function(e){
							for(var i=0;i<fieldList.length;i++){
								if(e.val == fieldList[i].id){
									var row = jQuery.extend(true, {}, fieldList[i]); 
									row.rid=row.id;
									row.id="";
									addRow('#insFieldList', insFieldRowIdx, insFieldTpl, row);
									if(row.type=='2'){
										$("#insFieldList"+insFieldRowIdx+"_numberButton").removeAttr("disabled");
									}else{
										$("#insFieldList"+insFieldRowIdx+"_numberButton").attr("disabled","disabled");
									}
									insFieldRowIdx = insFieldRowIdx + 1;
									//控制预录入域的可编辑状态
									$(".preInput:checked").each(function(){
										var val = $(this).val();
										if(val == "1"){
											var textarea = $(this).parent().next("span").find("textarea");
											textarea.removeAttr("disabled");
										}
									});
								}
							}
						});
						$("#fieldList").on("select2-removing",function(e){
							$(".rid").each(function(){
								if($(this).val()==e.val){
									$(this).parent().parent().remove();
								}
							});
						});
						for (var i=0; i<data.length; i++){
							addRow('#insFieldList', insFieldRowIdx, insFieldTpl, data[i]);
							insFieldRowIdx = insFieldRowIdx + 1;
						}
						//控制预录入域的可编辑状态
						$(".preInput:checked").each(function(){
							var val = $(this).val();
							if(val == "1" || val == "2"){
								var textarea = $(this).parent().next("span").find("textarea");
								textarea.removeAttr("disabled");
							}
						});
						$(".preInput").live("click",function(){
							var val = $(this).val();
							var textarea = $(this).parent().nextAll("span").find("textarea");
							if(val == "0"){
								textarea.attr("disabled","disabled");
							}else if(val == "1" || val == "2"){
								textarea.removeAttr("disabled");
							}
						});
						$(".indexed").live("click",function(){
							$(".dis").removeAttr("disabled");
							$(".hidden").val("0");
							var ind = $(this).attr("ind");
							var hidden = $(this).next("input[type=hidden]");
							if(this.checked || this.checked=='checked'){
								$(".indexed").removeAttr("checked");
								$(this).prop("checked",true);
								hidden.val("1");
								$("#r"+ind+"0").removeAttr("checked");
								$("#r"+ind+"1").attr("checked","checked");
								$("#u"+ind+"0").removeAttr("checked");
								$("#u"+ind+"1").attr("checked","checked");
								/* $("#r"+ind+"0").attr("disabled","disabled");
								$("#r"+ind+"1").attr("disabled","disabled");
								$("#u"+ind+"0").attr("disabled","disabled");
								$("#u"+ind+"1").attr("disabled","disabled"); */
							}
						});
						$(".fieldType").each(function(){
							var ind = $(this).attr("ind");
							if($(this).val()=='2'){
								$("#insFieldList"+ind+"_numberButton").removeAttr("disabled");
							}else{
								$("#insFieldList"+ind+"_numberButton").attr("disabled","disabled");
							}
						});
					});
					function useTemplate(){
						var id = $("#templates").val();
						var url = $("#ctx").val()+"/ins/insTable/getTemplate";
						//后台拿模板信息
						$.ajax({
			                type: 'POST',
			                url : url,
			                async:false,
			                data: {"templateId":id},             
			                success : function(data) {
			                	var fieldList = data.insFieldList;
			                	var name = data.name;
			                	var fullName = data.fullName;
			                	var category = data.category;
			                	if(fieldList != undefined && fieldList.length>0){
				                	$("#name").val(name);
				                	$("#fullName").val(fullName);
				                	deleteAll();
				                	for (var i=0; i<fieldList.length; i++){
				                		fieldList[i].id="";
										addRow('#insFieldList', insFieldRowIdx, insFieldTpl, fieldList[i]);
										insFieldRowIdx = insFieldRowIdx + 1;
									}
				                	if(data.category.id != ""){
					                	$("#parentId").val(data.category.id);
					                	$("#parentName").val(data.category.name);
				                	}
			                	}else{
			                		alertx("该模板中无参数");
			                	}
			                },
			                error : function(data){
			                	alertx("无权限");
			                }
			            });
					}
					function deleteAll(){
						$("#insFieldList tr").each(function(){
							var tr = $(this);
							var prefix = tr.prop("id");
							var close = tr.find(".close");
							tr.hide();
							$("#"+prefix+"_delFlag").val("1");
						});
					}
				</script>
			</div>
		</div>
		<div class="form-actions">
			<shiro:hasPermission name="ins:insTable:edit"><input id="btnSubmit" class="btn btn-primary" onclick="return servicePassword(submitForm,'${fns:getUser().name}');" type="button" value="保 存"/>&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form:form>
</body>
</html>